import { AuthService } from '../services/authService.js';
import { validateRequest, registerSchema, loginSchema, changePasswordSchema } from '../utils/validation.js';
import { formatSuccessResponse } from '../utils/errors.js';
import { authenticate } from '../middleware/auth.js';

export default async function authRoutes(fastify, options) {
  const authService = new AuthService(fastify.prisma, fastify.jwt);
  
  /**
   * 用户注册
   */
  fastify.post('/register', async (request, reply) => {
    const data = validateRequest(registerSchema, request.body);
    
    const user = await authService.register(
      data,
      request.ip,
      request.headers['user-agent']
    );
    
    return formatSuccessResponse(user, '注册成功');
  });
  
  /**
   * 用户登录
   */
  fastify.post('/login', async (request, reply) => {
    const data = validateRequest(loginSchema, request.body);
    
    const result = await authService.login(
      data,
      request.ip,
      request.headers['user-agent']
    );
    
    // 设置refreshToken到HttpOnly Cookie
    reply.setCookie('refreshToken', result.refreshToken, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'strict',
      path: '/',
      maxAge: 7 * 24 * 60 * 60, // 7天
    });
    
    return formatSuccessResponse({
      user: result.user,
      accessToken: result.accessToken,
    }, '登录成功');
  });
  
  /**
   * 刷新Token
   */
  fastify.post('/refresh', async (request, reply) => {
    const refreshToken = request.cookies.refreshToken;
    
    if (!refreshToken) {
      throw new Error('No refresh token provided');
    }
    
    const result = await authService.refreshToken(
      refreshToken,
      request.ip,
      request.headers['user-agent']
    );
    
    return formatSuccessResponse(result, 'Token刷新成功');
  });
  
  /**
   * 获取当前用户信息
   */
  fastify.get('/me', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const user = await fastify.prisma.user.findUnique({
      where: { id: request.user.userId },
      select: {
        id: true,
        username: true,
        email: true,
        role: true,
        is2faEnabled: true,
        createdAt: true,
        lastLogin: true,
      },
    });
    
    return formatSuccessResponse(user);
  });
  
  /**
   * 登出
   */
  fastify.post('/logout', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const sessionId = request.body.sessionId;
    
    await authService.logout(request.user.userId, sessionId);
    
    reply.clearCookie('refreshToken');
    
    return formatSuccessResponse(null, '登出成功');
  });
  
  /**
   * 登出所有设备
   */
  fastify.post('/logout-all', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const count = await authService.logoutAll(request.user.userId);
    
    reply.clearCookie('refreshToken');
    
    return formatSuccessResponse({ count }, `已登出${count}个设备`);
  });
  
  /**
   * 修改密码
   */
  fastify.put('/password', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const data = validateRequest(changePasswordSchema, request.body);
    
    await authService.changePassword(
      request.user.userId,
      data.oldPassword,
      data.newPassword
    );
    
    reply.clearCookie('refreshToken');
    
    return formatSuccessResponse(null, '密码修改成功，请重新登录');
  });
  
  /**
   * 获取活跃会话
   */
  fastify.get('/sessions', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const sessions = await fastify.prisma.userSession.findMany({
      where: {
        userId: request.user.userId,
        isActive: true,
        expiresAt: { gte: new Date() },
      },
      select: {
        id: true,
        deviceName: true,
        ipAddress: true,
        userAgent: true,
        lastActivity: true,
        createdAt: true,
      },
      orderBy: { lastActivity: 'desc' },
    });
    
    return formatSuccessResponse(sessions);
  });
  
  /**
   * 删除指定会话
   */
  fastify.delete('/sessions/:id', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    await fastify.prisma.userSession.delete({
      where: {
        id: request.params.id,
        userId: request.user.userId,
      },
    });
    
    return formatSuccessResponse(null, '会话已删除');
  });
  
  /**
   * 验证密码（敏感操作前）
   */
  fastify.post('/verify-password', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const { password } = request.body;
    
    const user = await fastify.prisma.user.findUnique({
      where: { id: request.user.userId },
    });
    
    const bcrypt = await import('bcrypt');
    const isValid = await bcrypt.compare(password, user.passwordHash);
    
    return formatSuccessResponse({ valid: isValid });
  });
}


